//
//  AppDelegate.m
//  BMProject
//
//  Created by MengHuan on 15/4/19.
//  Copyright (c) 2015年 MengHuan. All rights reserved.
//
//57c6401f3e546439a366cf55
//cffe72bbb57835f60e2f6ce1

#import "AppDelegate.h"
#import "Reachability.h"
#import "GuideView.h"
#import "JsonManager.h"
#import "AFNetworking.h"
#import "BMTabBar.h"
#import "HomeViewController.h"
#import "LoginViewController.h"
#import "UserModel.h"
#import "LocalStoreManager.h"
#import "IQKeyboardManager.h"
#import "OrderVc.h"
#import "JSONModel.h"
#import "StoresViewController.h"
#import "UIAlertView+ICBlockAdditions.h"
#import "BackgroundBizVc.h"
#import <AudioToolbox/AudioToolbox.h>
//#import "UMSocial.h"
//#import "UMSocialWechatHandler.h"//微信
//#import "UMSocialQQHandler.h"//qq
//#import "MobClick.h"

@interface AppDelegate ()<UITabBarControllerDelegate,TabBarViewDelegate>

// 网络状态实时监听
@property (strong, nonatomic) Reachability *reachability;

@end


@implementation NSURLRequest(DataController)
+ (BOOL)allowsAnyHTTPSCertificateForHost:(NSString *)host
{
    return YES;
}
@end


@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    // Override point for customization after application launch.
    // 申请本地通知权限
    if ([UIApplication instancesRespondToSelector:@selector(registerUserNotificationSettings:)]){
        [application registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound categories:nil]];
    }

    // Crash日志统计功能
    NSSetUncaughtExceptionHandler(&UncaughtExceptionHandler);

    // 实时监听网络状态
    [self startRealTimeNetworkStatus];

    // 构造window
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];

    // 显示window主窗口
    [self.window makeKeyAndVisible];

    // 设置rootViewController

    UserModel *model=  [[AppDelegate appDelegate] getUserInfo];
    if (model && model.username.length != 0 && model.pwd.length != 0) {
        //自动登陆
        [self setRootVC];
    }else{
        [[AppDelegate appDelegate] toLogin];
    }
//    [self setRootVC];

//    self.mainNavViewController      = [[MainNavViewController alloc]init];
//    self.window.rootViewController  = self.mainNavViewController;

    // 显示引导页
    //[self showGuideHUD];

//    设置友盟分享
//    [self setShare];
    // 显示水印
//    [self blueMobiWatermark];

    //状态栏字体颜色设置
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];

    // Override point for customization after application launch.

    NSString * isPushStr = DEF_PERSISTENT_GET_OBJECT(@"setting");
    if (isPushStr.integerValue == 1)
    {
        DEF_PERSISTENT_REMOVE(@"setting");
    }

    [self enableIQKeyboardManager];

    return YES;
}

/**
* 项目所有的 文本输入框 键盘自动撑起
*/
- (void)enableIQKeyboardManager {
    [[IQKeyboardManager sharedManager] setShouldToolbarUsesTextFieldTintColor:YES];
    [[IQKeyboardManager sharedManager] setCanAdjustTextView:YES];

    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    manager.enable = YES; //去掉这个参数,没有上一个下一个的,但可以
    manager.shouldResignOnTouchOutside = YES;
    manager.shouldToolbarUsesTextFieldTintColor = YES;
    manager.enableAutoToolbar = YES;
    [manager setPlaceholderFont:kFont(28.0f)];
    [manager setToolbarManageBehaviour:IQAutoToolbarByPosition];
    //Enabling keyboard manager
    [[IQKeyboardManager sharedManager] setKeyboardDistanceFromTextField:15];

    [[IQKeyboardManager sharedManager] disableToolbarInViewControllerClass:[OrderVc class]];//禁用Toolbar
    [[IQKeyboardManager sharedManager] disableInViewControllerClass:       [OrderVc class]];//

    [[IQKeyboardManager sharedManager] disableToolbarInViewControllerClass:[StoresViewController class]];//禁用Toolbar
    [[IQKeyboardManager sharedManager] disableInViewControllerClass:       [StoresViewController class]];//
}

/**
 *  登陆之后 (到主页)
 */
- (void)setRootVC
{

//    self.tabBarController = [[BMTabBar alloc] init];
//    self.tabBarController.delegate = self;
    HomeViewController * home = [[HomeViewController alloc]init];
    self.mainNavViewController = [[MainNavViewController alloc]initWithRootViewController:home];
    self.window.rootViewController = self.mainNavViewController;

    // 底部导航栏
//    self.tabBar = [[TabBarView alloc] initWithFrame:CGRectMake(0, kScreenHeight-48, kScreenHeight, 48)];
//    self.tabBar = [[TabBarView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 50)];

//    self.tabBar.delegate = self;
//    [self.tabBarController.tabBar addSubview:self.tabBar];

}

- (void)toLogin {
    LoginViewController *loginViewController=[[LoginViewController alloc]initWithNibName:@"LoginViewController" bundle:nil];
    self.window.rootViewController=loginViewController;
}

- (void)autologinAction:(UserModel *)userModel {
    [UserServices loginByUsername:userModel.username
                             pass:userModel.pwd
                  completionBlock:^(int result, id responseObject) {
                      if (result == API_Request_Success) {//必须要加不然别的错误就挂掉了
                          NSError *error;
                          responseObject = [NSJSONSerialization JSONObjectWithData:responseObject options:nil error:&error];
                          if (responseObject  && [responseObject isKindOfClass:[NSArray class]]) {
                              NSDictionary *dictionary = responseObject[0];
                              if ([dictionary objectForKey:@"msg"]) {
                                  [[AppDelegate appDelegate] toLogin];
                              } else {
                                  [SVProgressHUD showSuccessWithStatus:@"登录成功!"];
                                  UserModel *model = nil;
                                  model =  [[UserModel alloc] initWithDictionary:dictionary error:nil];
                                  model.username = userModel.username;
                                  model.pwd = userModel.pwd;
                                  model.griddingArea = dictionary[@"griddingArea"];
                                  [[AppDelegate appDelegate] setG_UserInfo:model];

                                  [[NSNotificationCenter defaultCenter] postNotificationName:DEFN_LOGIN_SUCESS object:nil userInfo:nil];
                              }
                          } else {
                              DLog(@"%@",error);
                              [[AppDelegate appDelegate] toLogin];
                          }
                      }
                  }];
}


//#pragma mark - 分享
//- (void)setShare
//{
//
//    [UMSocialData setAppKey:@"507fcab25270157b37000010"];
//
////    分享回调 设置  还有配置 URL scheme
//
//    [UMSocialWechatHandler setWXAppId:@"wxcf0a28c46f89485c" appSecret:@"d4624c36b6795d1d99dcf0547af5443d" url:nil];
//    [UMSocialQQHandler setQQWithAppId:@"1104870651" appKey:@"NciQTwyJ9V9XQw4j" url:nil];
//    [UMSocialQQHandler setSupportWebView:YES];
//}
//-(BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
//{
//    return [UMSocialSnsService handleOpenURL:url wxApiDelegate:nil];
//}
//-(BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
//{
//    return [UMSocialSnsService handleOpenURL:url];
//}
#pragma mark - TabBarViewDelegate
//- (void)tabBarView:(TabBarView *)tabBarView didSelectAtIndex:(NSInteger)index
//{
//    if (self.tabBarController.selectedIndex != index)
//    {
//
//        [self.tabBarController.selectedViewController.navigationController popToRootViewControllerAnimated:NO];
//        self.tabBarController.selectedIndex = index;
////        [self.tabBarController.tabBar bringSubviewToFront:self.tabBar];
//    }
//}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.

    NSString * loginStr = DEF_PERSISTENT_GET_OBJECT(@"login");
    NSString * gestureStr = DEF_PERSISTENT_GET_OBJECT(@"gesture");
    if ([loginStr isEqualToString:@"1"]&& [gestureStr isEqualToString:@"2"])
    {
        DEF_PERSISTENT_SET_OBJECT(@"1", @"gesture");
    }
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


#pragma mark -
+ (AppDelegate *)appDelegate
{
    return (AppDelegate *)[UIApplication sharedApplication].delegate;
}

#pragma mark - 显示引导页
- (void)showGuideHUD
{
    // 引导页
    if (![DEF_PERSISTENT_GET_OBJECT(@"showGuide") boolValue])
    {
        DEF_PERSISTENT_SET_OBJECT([NSNumber numberWithBool:YES], @"showGuide");
        GuideView *guide = [[GuideView alloc] initWithFrame:self.window.bounds];
        [self.window addSubview:guide];
    }
}

#pragma mark - 水印
- (void)blueMobiWatermark
{
    // 添加水印
    UIImageView *iv = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"blueMobiWatermark"]];
    iv.frame        = CGRectMake(0, 10, DEF_WIDTH(self.window), 12);
    [self.window addSubview:iv];
    [self.window bringSubviewToFront:iv];
}


#pragma mark -
#pragma mark - 实时监听网络状态

- (void)startRealTimeNetworkStatus
{
    // 开启网络状况的监听
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(reachabilityChanged:)
                                                 name:kReachabilityChangedNotification
                                               object:nil];
    self.reachability = [Reachability reachabilityWithHostName:@"www.baidu.com"];
    [self.reachability startNotifier];
}

- (void)reachabilityChanged:(NSNotification* )note
{
    Reachability *curReach  = [note object];
    NetworkStatus status    = [curReach currentReachabilityStatus];

    NSLog(@"网络状态值: %ld", (long)status);

    // 根据网络状态值，在这里做你想做的事
    // ...
}

#pragma mark -Crash日志

void UncaughtExceptionHandler(NSException *exception){
    NSArray *callStackArr = [exception callStackSymbols];
    NSString *reason = [exception reason];
    NSString *name = [exception name];
    NSMutableString *strSymbols = [NSMutableString string];

    for (int i = 0; i < callStackArr.count; i ++) {
        [strSymbols appendString:callStackArr[i]];
        [strSymbols appendString:@"\r\n"];
    }

    UIDevice *device = [UIDevice currentDevice];
    NSString *deInfo = [NSString stringWithFormat:@"%@,%@%@",device.model,device.systemName,device.systemVersion];

    NSDictionary *dictionary = @{@"DeviceInfo":deInfo,@"ExceptionName":name,@"ExceptionReason":reason,
                                 @"ExceptionCallStackInfo":strSymbols};
    NSString *filePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Caches/ExceptionLog"];
    [dictionary writeToFile:filePath atomically:YES];
}


- (UserModel *)getUserInfo {
    UserModel *model = [[LocalStoreManager shareInstance] getValueFromDefaultWithKey:DefaultKey_UserInfo];
    _g_UserInfo = model;
    return model;
}

- (void)setG_UserInfo:(UserModel *)g_UserInfo {
    _g_UserInfo = g_UserInfo;
    [[LocalStoreManager shareInstance] setValueInDefault:_g_UserInfo withKey:DefaultKey_UserInfo];
}


#pragma mark 接收到本地通知
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
    DLog(@"接收到本地通知:notification");

    //播放震动
    //AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);

    //播放震动 声音
    AudioServicesPlayAlertSound(kSystemSoundID_Vibrate);
    [self playVoice];

    [[UIAlertView alertViewWithTitle:@"提示"
                             message:@"你有未处理的后台业务"
                   cancelButtonTitle:@"取消"
                   otherButtonTitles:@[@"立即处理"]
                           onDismiss:^(NSInteger buttonIndex) {
                               [[UIApplication sharedApplication] cancelLocalNotification:notification];
                               BackgroundBizVc * bizVc = [[BackgroundBizVc alloc] init];
                               [self.mainNavViewController pushViewController:bizVc animated:YES];
                           }
                            onCancel:^{
                            }] show];

}

- (void)playVoice
{
    // 播放特定的声音
    static SystemSoundID soundIDTest = 0;
    NSString * path = [[NSBundle mainBundle] pathForResource:@"notifications" ofType:@"mp3"];
    NSLog([NSString stringWithFormat:@"播放特定的声音%@:", path]);
    if (path)
    {
        AudioServicesCreateSystemSoundID(nil, &soundIDTest );
    }
    else
    {
        AudioServicesPlaySystemSound(soundIDTest);
    }
}

@end
